package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import com.tbvtc.agriculturalcreditchainserver2025.dto.ali.AliYuYinDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.AliYuYin;
import com.tbvtc.agriculturalcreditchainserver2025.utils.HttpUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import com.tbvtc.agriculturalcreditchainserver2025.utils.aliyuyin.ByteRangeResource;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;

@RequestMapping("/ali")
@RestController
@Tag(name = "语音转换")
public class AliYuYinController {

    @Operation(summary= "需要转换的语音文本")
    @PostMapping("/testToVoice")
    public Result textToSpeech(@RequestBody AliYuYinDto dto) throws Exception{
        AliYuYin aliYuYin = BeanUtil.copyProperties(dto, AliYuYin.class);
        String pathName = UUID.randomUUID().toString();
        aliYuYin.setPathName(pathName);
        Map<String,String> query = new HashMap<>();
        Map<String,String> header = new HashMap<>();
        Map<String,String> body = new HashMap<>();
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(aliYuYin);
       stringObjectMap.forEach((key, value) -> body.put(key, value.toString()));

        HttpUtils.doPost("http://localhost:8080","/ali/tts","POST",header,query,body);
      return RUtils.success(pathName);
    }
    @GetMapping("/audio/{fileName}")
    @Operation(summary = "获取音频文件")
    public ResponseEntity<Resource> getAudioFile(@PathVariable String fileName) {
        try {
            // 音频文件路径（根据实际存储位置调整）
            // 方式1：项目resources目录下（打包后会在classpath中）
            // Resource resource = new ClassPathResource("static/audio/" + fileName + ".mp3");
            // 方式2：服务器绝对路径
            String filePath = "F:\\DeekSeep\\DK-AI\\src\\main\\resources\\wav\\" + fileName + ".mp3";
            Path path = Paths.get(filePath);
            if (!Files.exists(path)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            Resource resource = new FileSystemResource(path);

            // 设置响应头：指定音频格式、文件名
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("audio/mpeg"));
            headers.setContentDispositionFormData("attachment", fileName + ".mp3");

            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
}
